<?php
declare (strict_types = 1);

namespace app\admin\controller\system;

use app\admin\exception\ParameterException;
use app\admin\model\system\SystemUser as UserModel;
use app\admin\model\system\SystemUserRole;
use app\admin\model\system\SystemRole;
use app\admin\validate\system\User as UserValidate;
use think\Db;
use think\Exception;


class User extends Base
{
    
    public function index()
    {

        if ($this->request->isAjax())
        {
            $where = [];
            if ($search = input('get.username')) {
                $where[] = ['username', 'like', "%" . $search . "%"];
            }
           
            $list = UserModel::order('id','desc')
                ->where('id','>','1')
                ->field('password,rand_key,delete_time',true)
                ->where($where)
                ->paginate($this->request->get('limit'));

            return [
                'code' => 0,
                'msg' => '',
                'count' => $list->total(),
                'data' => $list->items(),
                'limit' => $this->request->get('limit')
            ];
        }
        return $this->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isAjax()) 
        {
            $data = $this->request->post();
            //验证
            $validate = new UserValidate;
            if(!$validate->scene('add')->check($data))
                throw new ParameterException($validate->getError());
            Db::startTrans();
            try {
                $password =  password_hash($data['password'],PASSWORD_DEFAULT);
                $adminUser = UserModel::create(array_merge($data, [
                    'password' => $password
                ]));
                $temp = [];
                foreach ($data['roles'] as $v){
                    $temp[] = [
                        'user_id' => $adminUser->id,
                        'role_id' => $v,
                    ];
                }
                $relationModel = new SystemUserRole();
                $relationModel->saveAll($temp);

                Db::commit();
            }catch (\Exception $e){
                Db::rollback();
                throw new Exception($e->getMessage());
            }
            return ['code'=>200,'msg'=>'添加成功'];
        }
        return $this->fetch('form',['roles' => SystemRole::all()]);
    }

    /**
     * 编辑
     */
    public function edit($id)
    {
        $formData = UserModel::with('roles')->where('id',$id)->find();

        if ($this->request->isAjax()) {
            //获取数据
            $data = $this->request->post();
            //验证
            $validate = new UserValidate;
            if(!$validate->scene('edit')->check($data)){
                throw new Exception($validate->getError());
            }  
            $formData->username = $data['username'];
            $formData->nickname = $data['nickname']; 
            $formData->status   = $data['status'] ?? 0;       
            
            Db::startTrans();
            try {
                //清除原先的角色
                SystemUserRole::where('user_id',$id)->delete();
                //添加新的角色
                $temp = [];
                foreach ($data['roles'] as $v){
                    $temp[] = [
                        'user_id' => $id,
                        'role_id' => $v,
                    ];
                }
                (new SystemUserRole())->saveAll($temp);
                $formData->save();
                Db::commit();
            }catch (\Exception $e){
                Db::rollback();
                throw new Exception($e->getMessage());
            }
            return ['code'=>200,'msg'=>'更新成功'];
            
        }
        $roles = SystemRole::select();
        foreach ($roles as $k=>$role){
            if (isset($formData->roles) && !$formData->roles->isEmpty()){
                foreach ($formData->roles as $v){
                    if ($role['id'] == $v['id']){
                        $roles[$k]['own'] = true;
                    }
                }
            }
        }
        return $this->fetch('form',[
            'formData' => $formData, 'roles' => $roles
        ]);
    }

    /**
     * 状态修改
     */
    public function edit_status()
    {
        if ($this->request->isAjax()) {
            $id = $this->request->post('id');
            $status = $this->request->post('status');
            
            $user = UserModel::get($id);
            if( $user == null ){
                throw new Exception('无效的请求');
            }
            $user->status = $status;
            $statusTxt = $status == 1 ? '启用' : '禁用';
            if( $user->save() == false ){
                throw new Exception($statusTxt . '失败');
            }
            return ['code'=>200,'msg' => $statusTxt . '成功'];
        }
    }

    /**
     * 删除
     */
    public function del($id)
    {
        $user = UserModel::find($id);
        if( $user == null ){
            throw new Exception('用户不存在');
        }
        try{
            //删除用户 删除中间表
            $user->delete();
            SystemUserRole::where('user_id', $user['id'])->delete();
            Db::commit();
        }catch (\Exception $e){
            Db::rollback();
            throw new Exception('删除失败');
        }
        return ['code'=>200,'msg'=>'删除成功'];
    }

    /**
     * 选中删除
     */
    public function del_all()
    {
        $ids = $this->request->param('ids');
        if (!is_array($ids)){
            throw new ParameterException('参数必须数组');
        }
        try{
            UserModel::destroy($ids);
            //删除中间表
            UserModel::whereIn('user_id', $ids)->delete();
            Db::commit();
        }catch (\Exception $e){
            Db::rollback();
            throw new Exception('删除失败');
        }
        return ['code'=>200,'msg'=>'删除成功'];
    }
}
